import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件
const Home = () => import("../components/Home")
const HomeNews = () => import("../components/HomeNews")
const HomeMessage = () => import("../components/HomeMessage")

const About = () => import("../components/About")
const User = () => import("../components/User")
const Profile = () => import("../components/Profile")

Vue.use(VueRouter)

const routes = [
  {
    path: '',
    redirect: '/home' 
  },
  {
    path: '/home',
    component: Home,
    meta: {title:'首页'},
    children: [
      {
        path: '',
        redirect: 'news'
      },
      {
        path: 'news',
        component: HomeNews
      },
      {
        path: 'message',
        component: HomeMessage
      }
    ]
  },
  {
    path: '/about',
    component: About,
    meta: {title:'关于'},
    // 路由独享守卫
    beforeEnter: (to, from, next)=>{
      console.log('beforeEnter---路由独享守卫');
      next();
    }
  },
  {
    // 如果不加/:userId,那只有/user才能显示组件,如果在浏览器中输入/user/lion是显示不出组件的,相当于通配符的作用
    path: '/user/:userId',
    component: User,
    meta: {title:'用户'},
  },
  {
    path: '/profile',
    component: Profile,
    meta: {title:'账号'},
  }
]

const router = new VueRouter({
  mode: 'history',
  routes
})
// 让跳转的网页标题显示路由meta对应的数据
// 前置守卫 (guard)  守卫实际上就是回调函数 , 前置守卫就是在路由跳转之前进行的回调函数
router.beforeEach((to,from,next)=>{
  document.title = to.matched[0].meta.title;
  console.log(to);
  next()
})


//后置钩子
router.afterEach((to,from)=>{
  console.log('后置钩子,在前置守卫执行后调用,没有next');
})
export default router
